<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="../modules/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../modules/fontawesome/css/all.min.css" />
    <script src="../modules/fontawesome/js/all.min.js"></script>
  </head>
  <body>
    <h2>用户管理</h2>
    <button data-action="addUser" class="btn btn-primary">添加</button>
    <!-- ------------- -->
    <form name="searchForm">
      <div class="row my-2 mx-2">
        <div class="col-2">
          <select class="form-select" name="searchField">
            <option value="name">用户名</option>
            <option value="email">邮箱</option>
            <option value="phone">手机</option>
          </select>
        </div>
        <div class="col-8">
          <input type="text" class="form-control" name="searchValue" />
        </div>
        <div class="col-2">
          <button class="btn btn-primary" type="button" data-action="searchBtn">
            搜索
          </button>
        </div>
      </div>
    </form>
    <!-- -------------------- -->
    <div id="usersBox"></div>

    <div id="usersPagination"></div>

    <script type="module">
      import { getUsers, on, deleteUserApi } from "./users.js";
      if (localStorage.userPage === undefined) {
        localStorage.userPage = 1;
      }

      getUsers(localStorage.userPage);

      on("input", {
        changeHeader() {
          // console.log(this.name);
          // console.log(this.checked);
          const tds = document.querySelectorAll(`[data-field="${this.name}"]`);
          if (this.checked === false) {
            [...tds].forEach((el) => (el.style.display = "none"));
          } else {
            [...tds].forEach((el) => (el.style.display = ""));
          }
        },
      });

      on("click", {
        searchBtn() {
          const field = document.searchForm.searchField.value;
          const value = document.searchForm.searchValue.value;
          const filter = value === "" ? "" : `(${field}~'${value}')`;
          getUsers(1, filter);
        },
        toPage() {
          const page = this.dataset.page;
          localStorage.userPage = page;
          getUsers(page);
        },
        editUser() {
          console.log("editUser");
        },
        deleteUser() {
          const id = this.dataset.id;
          if (confirm("确定删除吗？") === false) return;
          deleteUserApi(id);
        },
        addUser() {
          location.href = "./users-add.html";
        },
      });
    </script>
  </body>
</html>
